#/bin/bash

numbersFile="./numbers.txt"
dataDir="./data/"
imageDir="./images/"

command -v jq >/dev/null 2>&1 || { echo >&2 "getCards requires jq but it's not installed.  Aborting."; exit 1; }

for var in "$@"
do
    if [[ "$var" =~ ^"--numbersfile="(.+)$ ]] || [[ "$var" =~ ^"--n="(.+)$ ]] ; then
        numbersFile=${BASH_REMATCH[1]}
    elif [[ "$var" =~ ^"--datadir="(.+)$ ]] || [[ "$var" =~ ^"--d="(.+)$ ]] ; then
        dataDir="${BASH_REMATCH[1]}"
    elif [[ "$var" =~ ^"--imagedir="(.+)$ ]] || [[ "$var" =~ ^"--i="(.+)$ ]] ; then
        imageDir="${BASH_REMATCH[1]}"
    elif [[ "$var" =~ ^"--"(set|s)"="(.+)""$ ]] ; then
        set=${BASH_REMATCH[2]}
    else
        echo "unknown argument $var"
        echo "Usage: bash getData.sh --multiverseid=<number>"
        exit 1
    fi
done

if [[ -z $set ]] ; then
    echo "Error: set not set"
    exit 1
else 
    echo $set;
fi

scriptDir=`realpath -s $0`
scriptDir=${scriptDir%\/*}"/"
echo $scriptDir

numbers=`bash $scriptDir/getNumbers.sh --s="$set"` || { echo -e "Could nog retrieve numbers => \n\t"$numbers; exit 1; }

echo $numbers > "$numbersFile";

mkdir -p "$dataDir"
mkdir -p "$imageDir"

while read line ; do
    for number in $line ; do
        bash $scriptDir/getData.sh --m=$number --o=$dataDir
    done
done < "$numbersFile"

for file in $dataDir/*.json ; do
    
    number=${file%.*}
    number=${number##*\/}
    
    name=`cat $file | jq '.name'`
    name=${name// /_}
    name=${name//Æ/"&AElig;"}
    name=${name//\"/}
    
    bash $scriptDir/getImage.sh --m=$number --o=$imageDir --n=$name"_"$number".jpg"
done
